package com.gaoyi.basemodule.baseact;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.gaoyi.basemodule.basebean.Event;
import com.gaoyi.basemodule.baseconstant.EventCode;
import com.gaoyi.basemodule.baseUtil.ActivityUtil;
import com.gaoyi.basemodule.baseUtil.LanguageUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.Map;

public abstract class BasePermissionActivity extends AppCompatActivity {

    protected ActivityResultLauncher<String[]> mPermissionsResult;
    private WeakReference<AppCompatActivity> mWeakReference = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (mWeakReference == null) {
            mWeakReference = new WeakReference<>(this);
        }
        ActivityUtil.getInstance().addActivity(mWeakReference.get());
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LanguageUtils.getInstance().change(LanguageUtils.getInstance().getCurrentLanguage()));
    }

    protected abstract void event(Event event);

    protected abstract void onRequestPermissionsResult(Map<String, Boolean> result);

    protected abstract void onActivityResult(int requestCode, ActivityResult result);

    protected ActivityResultLauncher<Intent> registerForActivityResult(int requestCode) {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> onActivityResult(requestCode, result));
    }

    protected ActivityResultLauncher<String[]> registerForPermissionsResult() {
        return registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), this::onRequestPermissionsResult);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_LANGUAGE) {
            recreate();
        } else {
            event(event);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityUtil.getInstance().removeActivity(mWeakReference.get());
        ActivityUtil.getInstance().removeFragment(mWeakReference.get());
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

}
